package com.andrewdashin.twit2jabber.services.impl;

import com.andrewdashin.twit2jabber.services.JabberService;
import org.jivesoftware.smack.*;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;
import org.springframework.beans.factory.annotation.Required;

/**
 * User: dashin
 * Date: 26.11.2009
 * Time: 11:05:02
 */
public class JabberServiceImpl implements JabberService {

    private String botServerHost;
    private int botServerPort;
    private String botUserName;
    private String botPassword;
    private String botStatus;

    private XMPPConnection xmppConnection;

    private synchronized boolean connectIfNeeded() {
        if (xmppConnection == null) {
            xmppConnection = new XMPPConnection(new ConnectionConfiguration(botServerHost, botServerPort));
        }
        return xmppConnection.isConnected() || doConnect();
    }

    private boolean doConnect() {
        try {
            xmppConnection.connect();
            SASLAuthentication.supportSASLMechanism("PLAIN", 0);
            xmppConnection.login(botUserName, botPassword, "twit2j");
            Presence p = new Presence(Presence.Type.available);
            p.setStatus(botStatus);
            xmppConnection.sendPacket(p);
        } catch (XMPPException e) {
            // TODO make logging
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public void keepConnectionAlive() {
        connectIfNeeded();
    }

    @Override
    public void sendMessage(String recipientUserName, String message, MessageListener callback) {
        if (connectIfNeeded()) {
            ChatManager chatmanager = xmppConnection.getChatManager();;
            Chat newChat = chatmanager.createChat(recipientUserName, callback);
            try {
                newChat.sendMessage(message);
            } catch (XMPPException e) {
                e.printStackTrace();
            }
        }
    }

    @Required
    public void setBotServerHost(String botServerHost) {
        this.botServerHost = botServerHost;
    }

    @Required
    public void setBotServerPort(int botServerPort) {
        this.botServerPort = botServerPort;
    }

    @Required
    public void setBotUserName(String botUserName) {
        this.botUserName = botUserName;
    }

    @Required
    public void setBotPassword(String botPassword) {
        this.botPassword = botPassword;
    }

    @Required
    public void setBotStatus(String botStatus) {
        this.botStatus = botStatus;
    }

}
